<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of sealplayer
 *
 * @author Samuel
 */
class broadcastmamage_controller extends Controller {

    private $type_array;

    function _init() {
        check_level(50, segment(0), segment(1), segment(2, 'index'));
        $this->type_array = array("0" => translate('MENU_broadcast_now'), "1" => translate('MENU_broadcast_once'), "2" => translate('MENU_broadcast_everyday'), "3" => translate('MENU_broadcast_everyweek'));
        $this->state_array = array(0 => translate("CLOSE"), 1 => translate("OPEN"), 2 => translate("EXPIRE"));
        $this->state_color = array(0 => "FF0000", 1 => "999999", 2 => "FF0000");
        $this->frequence = array('once' => translate('ONCE'), 'repeat' => translate('REPEAT'), 'now' => translate('RIGHT_NOW'));
        $this->channel = array(5 => translate('BROADCAST_CHANNEL_SYSTEM'), 7 => translate('BROADCAST_CHANNEL_BROADCAST'));
    }

    function index() {//var_dump($_SESSION['pizi']);
        $areahostArray = get_area_list_option();
        $selectedArea = $_SESSION['area_selected_id'];
        $this->view->assign("arealist", $this->form->select("area_selected_id", $areahostArray, $selectedArea, array('id' => 'area_selected_id')));
        $this->view->display("broadcast/broadcastmamage/index");
    }

    function flexigrid() {
        list($colkey, $colsinfo, $where, $sortname, $sortorder, $offset, $rp, $page) = $this->common->get_flexigrid_params();

        $area_id_2_name = get_area_list_option();
        $rows = array();

        $sql = "SELECT COUNT(*) AS num FROM {pre}broadcast WHERE {$where}";
        $one = $this->db->one($sql);
        $total = $one['num'];
        $orderby = $sortname ? "ORDER BY {$sortname} {$sortorder} " : "";
        $sql = "SELECT {$colsinfo} FROM {pre}broadcast WHERE {$where} ORDER BY {$sortname} {$sortorder}  LIMIT {$offset},{$rp}";
        $this->db->query($sql);
        while ($row = $this->db->get_array()) {
            if ($row['area'] != "0") {
                $area_array = explode(',', $row['area']);

                foreach ($area_array as $key => $value) {
                    $area_name_array[] = $area_id_2_name[$value];
                }
                $row['area'] = implode(',', $area_name_array);
                unset($area_name_array);
            } else {
                $row['area'] = translate("ALL_AREA");
            }
            $content = get_json_var($row['content']);
            $row['content'] = $content['msg'];

            $channels = explode(',', $row['channel']);
            unset($row['channel']);
            foreach ($channels as $key => $value) {
                $row['channel'] .= $this->channel[$value] . " ";
            }
            unset($channels);
            $row['expiretime'] = $row['expiretime'] ? get_datetime($row['expiretime']) : translate('NOEXPIRE');
            $row['executetime'] = $row['executetime'] ? get_datetime($row['executetime']) : translate('UNDONE');
            $row['frequence'] = $this->frequence[$row['frequence']];
            $rows[] = array('id' => $row['id'], 'cell' => ($row));
        }
        $result = array(
            'page' => $page,
            'total' => $total,
            'rows' => $rows
        );
        echo json_encode($result);
    }

    function add($id = 0) {
        $area_id = get_area_list_option();

        if (is_submit()) {
            $rowdata = $_POST['row'];
            
            $areaIds = $_POST['areaIds'];
            
            $rowdata['createtime'] = time();
            $rowdata['starttime'] = $rowdata['starttime'] ? strtotime($rowdata['starttime']) : 0;
            $rowdata['expiretime'] = $rowdata['expiretime'] ? strtotime($rowdata['expiretime']) : 0;
            $rowdata['state'] = 1;
            
            $rowdata['repeatCount'] = 0;  //表示持续
            $rowdata['interval'] = 0;  //表示持续
            //print_r($rowdata);
            
            //如果是立即推送
            if ($rowdata['frequence'] == 'now') {
                $errorResultS = array();
                $pack['word'] = $rowdata['content']['msg'];
                $pack['repeatCount'] = $rowdata['repeatCount'];  //表示持续
                $pack['interval'] = $rowdata['interval'];
                foreach ($rowdata['channel'] as $k => $v) {
                    $k = ($k + 1);
                    $pack["channel$k"] = $v;
                }
                $str = array_to_stringparam($pack);
                //print_r($str);
                //exit(0);
                if (in_array('0', $areaIds)) {
                    $liveAreas = get_area_list_live();
                    foreach ($liveAreas as $k => $v) {
                        $strS = $v['host'] . $str . "action=19";
                        
                        $strResultStr = vpost($strS);
                        //echo " all area $strS result = $strResultStr ";
                        
                        if ($strResultStr != '0' || $strResultStr === FALSE) {
                            $errorResultS[] = $area_id[$k];
                        }
                    }
                } else {
                    $area_host = get_area_list_url();
                    //print_r($area_host);
                    foreach ($areaIds as $key => $value) {
                        $strS = $area_host[$value] . $str . "action=19";
                        //print_r($strS);
                        //exit(0);
                        $strResultStr = vpost($strS);
                        //print_r($strResultStr);
                        //exit(0);
                        //$strResultStr == false ? print_r("+") : print_r("-");
                        //exit(0);
                        //echo " select area $strS result = $strResultStr ";
                        
                        if ($strResultStr != '0' || $strResultStr === FALSE) {
                            $errorResultS[] = $area_id[$key];
                        }
                    }
                }

                //操作失败或者连接失败
                if (count($errorResultS) > 0) {
                    $string = implode(',', $errorResultS) . "广播失败！";
                    echo "<script>alert('" . $string . "');</script>";
                }else{
                    $rowdata['state'] = 2;
                }
            }

            //如果是所有区
            if (in_array('0', $areaIds)) {
                $strAreas = '0';
            } else {
                $strAreas = implode(",", $areaIds);
            }
            $rowdata['area'] = $strAreas;
            $rowdata['content'] = addslashes(json_encode($rowdata['content']));
            $rowdata['channel'] = implode(",", $rowdata['channel']);
            
            $this->db->insert('{pre}broadcast', $rowdata);
            insert_log(translate('MENU_BROADCAST_BROADCASTMAMAGE'),translate('ADD'), NULL, array("name" => $rowdata['word']));

            cp_tips($result == 0 ? "success" : "error");
        }else 
        {
	        set_area_list_view("arealist");
	
	        $this->view->assign("frequence", $this->form->select("row[frequence]", $this->frequence, array(), array('id' => 'frequence')));
	        $this->view->assign("type_array", $this->form->select("row[type]", $this->type_array, '', array('id' => 'type')));
	        $this->view->display("broadcast/broadcastmamage/add");
        }
    }

    function edit($id = 0) {
        if ($id === 0)
            error(translate('C_INVALID_PARAM_ID', $id));
        $row = $this->db->one("SELECT * FROM {pre}broadcast WHERE id='{$id}'");
        if (is_submit()) {
            $rowdata = $_POST['row'];
            $rowdata['content'] = addslashes(json_encode($rowdata['content']));
            $rowdata['starttime'] = strtotime($rowdata['starttime']);
            $rowdata['expiretime'] = strtotime($rowdata['expiretime']);
            $rowdata['channel'] = implode(",", $rowdata['channel']);
            $this->db->update('{pre}broadcast', $rowdata, array('id' => $id));
            insert_log(translate('MENU_BROADCAST_BROADCASTMAMAGE'),translate('EDIT'), NULL, array("name" => $rowdata['word']));

            cp_tips($result == 0 ? "success" : "error");
        }
        unset($this->type_array['0']);
        $row['content'] = get_json_var($row['content']);
        $row['channel'] = explode(",", $row['channel']);
        $this->view->assign("row", $row);
        $this->view->assign("frequence", $this->form->select("row[frequence]", $this->frequence, $row['frequence'], array('id' => 'frequence')));
        $this->view->assign("type_array", $this->form->select("row[type]", $this->type_array, $row['type'], array('id' => 'type')));
        $this->view->display("broadcast/broadcastmamage/edit");
    }

    function del($id = 0) {
        $c = 0;
        $r = '';
        if ($id === 0)
            json_output($c, translate('C_INVALID_PARAM_ID', $id));
        $row = $this->db->one("SELECT * FROM {pre}broadcast WHERE id='{$id}'");
        if (!is_array($row))
            json_output($c, translate('C_INVALID_PARAM_ID', $id));
        if ($this->db->delete('{pre}broadcast', array('id' => $id))) {
            insert_log(translate('MENU_BROADCAST_BROADCASTMAMAGE'),translate('DEL'), array('id'=> $id));
            $c = 1;
        } else {
            $r = translate('C_TIPS_ERROR_TEXT');
        }
        json_output($c, $r);
    }

    function multi() {
    	//print_r($_POST);
    	$type = $this->input->post("type");
    	$ids = $this->input->post("ids");
    	$c = 0;
    	$r = '';
    	//echo " type = $type ";
    	//echo " ids = $ids ";
    	if (count(explode(',', $ids)) == 0) {
    		$r = translate('C_INVALID_PARAMS');
    	} else
    	{
    		if ($type == 'delete') {
    			$sql = "DELETE FROM {pre}broadcast WHERE id IN ({$ids})";
    			//echo " sql = $sql ";
    			$this->db->query($sql);
    			$c = 1;
    		} else
    		{
    			$r = translate('C_INVALID_PARAMS');
    		}
    	}
    	json_output($c, $r);
    		
    }
    
}

?>
